<?php
namespace Home\Controller;
use Home\Biz\AdminBiz;
use Home\Biz\MeetingBiz;
use Home\Biz\VoteBiz;
use Home\Biz\WechatBiz;
use Think\Controller;

class WechatController extends BaseController {
	
	
	
	/**
	 * Description: 会议签到
	 * @version 2016年9月22日 下午3:26:44 
	 * @author lin.yujiao@whaley.cn
	 */
	public function meetingSignIn(){
		//通过GET请求获取从微信认证的CODE并发起请求获取企业accessToken
		$code = $_GET["code"];
		$meeting_key = $_GET["meeting_key"];
		$user = WechatBiz::getCompanyContact($code);
		if(empty($user)){
			$msg = '用户未在企业微信中认证,请先认证后签到';
		}else if($user == -1){
			$msg = '微信参数错误,获取数据失败';
		}else{
			$meeting = MeetingBiz::existMeeting();
			$msg = MeetingBiz::baseValidate($meeting, $user , $meeting_key);
			if(empty($msg)){
				$user_id = $user['userid'];
				$user_name	= $user['name'];
				$this->getLocation($access_token,$user_id,$user_name,$meeting['meeting_id']);
				return;
			}
		}
		//错误情况
		$this->showError($msg);
		return;
	}

	/**
	 * Description: 获取微信JS配置跳转页面利用JS调用获取用户当前坐标
	 * @version 2016年9月23日 上午11:23:56 
	 * @author lin.yujiao@whaley.cn
	 */
	public function getLocation($access_token, $user_id, $user_name, $meeting_id) {
		$wx_config = WechatBiz::getWeichatJsConfig($access_token);
		$this->assign('wx_config', json_encode($wx_config));
		$this->assign('user_id', $user_id);
		$this->assign('user_name', $user_name);
		$this->assign('meeting_id', $meeting_id);
		$this->display ( "wechat/get_location_info" );
	}
	/**
	 * Description: 执行签到
	 * @version 2016年9月23日 下午4:17:23 
	 * @author lin.yujiao@whaley.cn
	 */
	public function doMeetingSignIn(){
		$meeting_id = $_GET["meeting_id"];//会议ID
		$user_id = $_GET["user_id"];//员工编码
		$user_name = $_GET["user_name"];//员工编码
		$longitude = $_GET["longitude"];//经度
		$latitude = $_GET["latitude"];//纬度
		$meeting = MeetingBiz::loadMeeting($meeting_id);
		$response = MeetingBiz::doMeetingRecord($meeting, $user_id, $user_name, $latitude, $longitude);
		if($response['isSuccess'] == true){
			$this->showMsg($response['msg'], "会议签到");
		}else{
			$this->showError($response['msg']);
		}
		return;
	}
    /**
     * Description: 获取标签内成员
     * @version 2016年9月22日 下午4:38:28 
     * @author lin.yujiao@whaley.cn
     */
	public function getTagMember(){
		//通过GET请求获取从微信认证的CODE并发起请求获取企业accessToken
		$tag_name = $_GET["tag_name"];
		if(!empty($tag_name)){
			$access_token = WechatBiz::accessToken();
			$tag_member_result = WechatBiz::getTagMemberList($access_token, $tag_name);
			$this->responseSuccess($tag_member_result);
			return ;
		}
	}
	
    /**
     * Description: 企业号获取登录信息及通讯录信息
     * @version 2016年8月30日 下午2:33:24 
     * @author lin.yujiao@whaley.cn
     */
    public function quickLogin(){
    	//通过GET请求获取从微信认证的CODE并发起请求获取企业accessToken
    	$code = $_GET["code"];
    	$access_token = WechatBiz::accessToken();
    	if(!empty($code) && !empty($access_token)){
    		//通过CODE与TOKEN获取当前登录的企业用户ID
    		$user_url  = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=$access_token&code=$code";
    		$user_result = WechatBiz::getUserinfo($access_token,$code);
    		$open_id = $user_result['UserId'];
    		if(!empty($open_id)){
    			//通过用户ID访问通讯录获取详细通讯录内的详细信息
    			$company_user_result = WechatBiz::getContactinfo($access_token, $open_id);
		   		if(!empty($company_user_result) && !empty($company_user_result['userid']) && !empty($company_user_result['name'])){
		   			$user_id	= $company_user_result['userid'];
		   			$user_name	= $company_user_result['name'];
		   			$create_user	= 'whaleyFZ AjaxService adminService.employeeLogin';
		   			//利用详细信息在O2O平台中进行快捷登录若操作成功跳转至首页
		   			if(AdminBiz::employeeSimpleLogin($user_id, $user_name, $create_user)){
		   				redirect(C('UrlConfig.home_url'));
		   				return;
		   			}
		   		}
    		}
    	}
    	redirect(C('UrlConfig.audit_error_url').'?type=4');
    	return;
   	}
   	
   	/**
   	 * Description: 展示投票主题
   	 * @version 2016年11月24日 下午2:37:55 
   	 * @author lin.yujiao@whaley.cn
   	 */
   	public function showVote(){
   		//通过GET请求获取从微信认证的CODE并发起请求获取企业accessToken
   		$code = $_GET["code"];
   		$vote_id = $_GET["vote_id"];
   		$user = WechatBiz::getCompanyContact($code);
   		if(empty($user)){
   			$msg = '用户未在企业微信中认证,请认证后重试';
   		}else if($user == -1){
   			$msg = '微信参数错误,获取数据失败';
   		}else{
   			$vote_info = VoteBiz::getFullVoteInfo($vote_id);
   			$msg = VoteBiz::baseValidate($vote_info);
   			if(empty($msg)){
   				$this->assign('user_id', $user['userid']);
   				$this->assign('user_name', $user['name']);
   				$this->assign('vote_info', $vote_info);
   				$this->assign('input_type', ($vote_info['check_box_max'] > 1 ? 'checkbox' : 'radio'));
   				$this->display( "wechat/show_vote" );
   				return;
   			}
   		}
   		//错误情况
   		$this->showError($msg);
   		return;
   	}
   	/**
   	 * Description: 执行投票
   	 * @version 2016年11月25日 下午3:31:27 
   	 * @author lin.yujiao@whaley.cn
   	 */
   	public function doVote(){
   		$vote_id = $_GET["vote_id"];//投票
   		$user_id = $_GET["user_id"];//员工编码
   		$user_name = $_GET["user_name"];//员工名称
   		$item_ids = $_GET["item_ids"];//投票项
   		$arr_ids = explode(",",$item_ids);
   		$response = VoteBiz::doVote($vote_id, $user_id, $user_name, $arr_ids);
   		if($response['isSuccess'] == true){
   			$this->showMsg($response['msg'], "投票调研");
   		}else{
   			$this->showError($response['msg']);
   		}
   		return;
   	}
/*    	public function testVote(){
   			$vote_info = VoteBiz::getFullVoteInfo('VT11186087');
   			$msg = VoteBiz::baseValidate($vote_info);
   			if(empty($msg)){
   				$this->assign('user_id', $user['userid']);
   				$this->assign('user_name', $user['name']);
   				$this->assign('vote_info', $vote_info);
   				$this->assign('input_type', ($vote_info['check_box_max'] > 1 ? 'checkbox' : 'radio'));
   				$this->display( "wechat/show_vote" );
   				return;
   			}
   		//错误情况
   		$this->showError($msg);
   		return;
   	} */
    /**
     * Description: 个人微信登录信息获取
     * @version 2016年8月31日 上午9:53:39 
     * @author lin.yujiao@whaley.cn
     */
    public function testPersonWeixin(){
    	$refresh_flag = false;
    	$appid = 'wx22637ce143759407';
    	$secret = '94bda3999ba3092e2fe9765cd7f8b77a';
    	$code = $_GET["code"];
    	echo "<br/>第一步 获取CODE:";
    	if(empty($code)){
    		echo "获取失败";
    		return;
    	}
    	echo "<br/>";
    	echo json_encode($code);
    	
    	echo "<br/><br/>第二步 根据CODE发起GET请求获取TOKEN信息:";
    	$token_url  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    	$token_result = json_decode(file_get_contents($token_url), true);
    	if(empty($token_result)){
    		echo "获取失败";
    		return;
    	}
    	$access_token = $token_result['access_token'];
    	$refresh_token = $token_result['refresh_token'];
    	$openid = $token_result['openid'];
    	echo "<br/>access_token:";
    	echo $access_token;
    	echo "<br/>expires_in:";
    	echo $token_result['expires_in'];
    	echo "<br/>refresh_token:";
    	echo $refresh_token;
    	echo "<br/>openid:";
    	echo $openid;
    	echo "<br/>scope:";
    	echo $token_result['scope'];
    	//若需要刷新token
    	if($refresh_flag){
    		echo "<br/><br/>第三步 根据REFERSH_TOKEN发起GET请求刷新TOKEN信息:";
    		$refresh_url  = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
    		$refresh_result = json_decode(file_get_contents($refresh_url), true);
    		if(empty($refresh_result)){
    			echo "获取失败";
    			return;
    		}
    		$access_token = $refresh_result['access_token'];
    		$refresh_token = $refresh_result['refresh_token'];
    		$openid = $refresh_result['openid'];
    		echo "<br/>access_token:";
    		echo $access_token;
    		echo "<br/>expires_in:";
    		echo $refresh_result['expires_in'];
    		echo "<br/>refresh_token:";
    		echo $refresh_token;
    		echo "<br/>openid:";
    		echo $openid;
    		echo "<br/>scope:";
    		echo $refresh_result['scope'];
    	}
    	
    	//拉取用户信息(需scope为 snsapi_userinfo)
    	echo "<br/><br/>最后 拉取用户信息(需scope为 snsapi_userinfo):";
    	$user_result = WechatBiz::getUserinfo($access_token,$code);
    	if(empty($user_result)){
    		echo "获取失败";
    		return;
    	}
    	echo "<br/>openid:";
    	echo $user_result['openid'];
    	echo "<br/>nickname:";
    	echo $user_result['nickname'];
    	echo "<br/>province:";
    	echo $user_result['province'];
    	echo "<br/>city:";
    	echo $user_result['city'];
    	echo "<br/>country:";
    	echo $user_result['country'];
    	echo "<br/>headimgurl:";
    	echo $user_result['headimgurl'];
    	echo "<br/>privilege:";
    	echo $user_result['privilege'];
    	echo "<br/>unionid:";
    	echo $user_result['unionid'];
    	//附：检验授权凭证（access_token）是否有效
    	//https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
    	//正确的Json返回结果：{ "errcode":0,"errmsg":"ok"}
    	//错误时的Json返回示例：{ "errcode":40003,"errmsg":"invalid openid"}
    }
    /**
     * Description: json返回成功
     * @version 2016年9月23日 上午10:57:01 
     * @author lin.yujiao@whaley.cn
     */
    public function responseSuccess($result){
    	//0，正确；1，参数错误；2,安全码校验失败;3，无法反序列化；4,服务器错误;5，业务逻辑错误
    	$return_json = array(
    			'IsSuccess' => 1,
    			'ErrorMsg' => '',
    			'ErrorCode' => 0,
    			'Result' => $result,
    	);
    	$this->ajaxReturn($return_json);
    }
    /**
     * Description: 展示错误信息
     * @version 2016年9月23日 上午10:56:50 
     * @author lin.yujiao@whaley.cn
     */
    public function showError($msg) {
    	$this->assign('msg', $msg);
    	$this->display ( "wechat/error" );
    }
    /**
     * Description: 展示错误信息
     * @version 2016年9月23日 上午10:56:50 
     * @author lin.yujiao@whaley.cn
     */
    public function showMsg($msg,$title) {
    	$this->assign('msg', $msg);
    	$this->assign('title', $title);
    	$this->display ( "wechat/message" );
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public function _test_demo(){
    	//通过GET请求获取从微信认证的CODE并发起请求获取企业accessToken
    	$code = $_GET["code"];
    	$meeting_key = $_GET["meeting_key"];
    	$access_token = WechatBiz::accessToken();
    	if(!empty($code) && !empty($access_token)){
    		//通过CODE与TOKEN获取当前登录的企业用户ID
    		$user_result = WechatBiz::getUserinfo($access_token,$code);
    		$open_id = $user_result['UserId'];
    		if(!empty($open_id)){
    			//通过用户ID访问通讯录获取详细通讯录内的详细信息
    			$company_user_result = WechatBiz::getContactinfo($access_token, $open_id);
    			if(!empty($company_user_result) && !empty($company_user_result['userid']) && !empty($company_user_result['name'])){
    				//正确情况
    				$tag_member_result = WechatBiz::getTagMemberList($access_token, '测试会议');
    				if(!empty($tag_member_result)){
    					$user_id	= $company_user_result['userid'];
    					$user_name	= $company_user_result['name'];
    					$allow_flag = false;
    					foreach ($tag_member_result as $index => $object){
    						if($object["userid"] == $user_id){
    							$allow_flag = true;
    							break;
    						}
    					}
    					if($allow_flag){
    						$this->getLocation($access_token,$user_id,$user_name,$meeting_key);
    					}else{
    						//错误情况
    						$this->showError($company_user_result['name'] . '无权签到');
    					}
    					return;
    				}
    			}
    		}
    	}
    	//错误情况
    	$this->showError('错误:无法签到');
    	return;
    }
}